package com.example.simplenet;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class AbandonedFragment extends MyFragment {
	
	private TextView mAbandonedTextView = null;
	private LinearLayout mContainerLayout = null;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
	
		View view = inflater.inflate(R.layout.abandoned_fragment, container,
				false);
		return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
	
		mAbandonedTextView = (TextView) getView().findViewById(
				R.id.abandonedTextView);
		mAbandonedTextView.setText(AbandonedController.getInstance(getActivity())
				.getText());
		mContainerLayout = (LinearLayout) getView().findViewById(
				R.id.abandonedContainerLayout);
		layout();
		super.onActivityCreated(savedInstanceState);
	}
	
	public void setText(String text) {
	
		mAbandonedTextView.setText(text);
	}
	
	public void layout() {
	
		ArrayList<AbandonedInfo> recentlyAbandoned = AbandonedController
				.getInstance(getActivity()).getAbandoned();
		if (recentlyAbandoned == null)
			return;
		Collections.sort(recentlyAbandoned, mDateComparator);
		if (recentlyAbandoned != null && mContainerLayout != null
				&& recentlyAbandoned.size() > mContainerLayout.getChildCount()) {
			mContainerLayout.removeAllViews();
			Calendar now = Calendar.getInstance();
			now.add(Calendar.HOUR, -12);
			Date comp = now.getTime();
			for (AbandonedInfo info : recentlyAbandoned) {
				if (info.getDate().before(comp))
					continue;
				Button button = new Button(getActivity());
				button.setTag(info.getName());
				button.setText(info.getName() + " - "
						+ info.getDistance() + " ("
						+ info.getPoints() + " pts)");
				mContainerLayout.addView(button, new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				mContainerLayout.invalidate();
			}
		}
		
	}
	
	private DateComparator mDateComparator = new DateComparator();
	
	private class DateComparator implements Comparator<AbandonedInfo> {

		@Override
		public int compare(AbandonedInfo lhs, AbandonedInfo rhs) {
			if (lhs.getDate() == null)
				return -1;
			if (rhs.getDate() == null)
				return 1;
			int i = lhs.getDate().compareTo(rhs.getDate());
			return -i;
		}
		
	}
	
}
